#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h> //struct addr_in
#include <arpa/inet.h>

#define ip "192.168.0.191"
#define port 8080
//socket编程:获取网络套接字：描述符
int main()
{   
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock == -1)
    {
        perror("socket");
        return -1;
    }
    
    // char msg[100] = "helloworld";
    
    
    //地址结构体赋值
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip);
    
    //绑定端口号
    if(bind(sock,(struct sockaddr*)&addr,sizeof(addr))<0)
    {
        perror("bind");
        return -1;
    }
    // //发送数据
    // if(sendto(sock,msg,100,0,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    // {
    //     perror("sendto");
    //     return -1;
    // }

    // printf("发送成功!\n");
    
    char msg[100] = {0};
    socklen_t len = sizeof(addr);
    if(recvfrom(sock,msg,100,0,(struct sockaddr*)&addr,&len) < 0)
    {
        perror("recvfrom");
        return -1;
    }
    printf("收到来自ip:%s端口:%d 的信息:%s\n",inet_ntoa(addr.sin_addr),ntohs(addr.sin_port),msg);
    return 0;
}